package com.sc.collection.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.concurrent.TimeUnit;

/**
 * @author shuchang
 * @Date 2018/3/18 下午8:24
 */
@Service
public class CollectionServiceImpl implements WeatherDataCollectionService{

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String WEATHER_URL="http://wthrcdn.etouch.cn/weather_mini?";

    @Override
    public void syncDataByCityId(String cityId) {
        String uri = WEATHER_URL+"citykey="+cityId;
        saveWeatherData(uri);
    }


    private void saveWeatherData(String uri){
        String body = "";
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        ResponseEntity<String> entity = restTemplate.getForEntity(uri, String.class);
        if(entity.getStatusCodeValue()==200){
            body = entity.getBody();
        }
        opsForValue.set(uri,body,60*60, TimeUnit.SECONDS);
    }
}
